package cn.tomoki.myapplication;

import android.app.Dialog;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import cn.tomoki.config.URL;
import cn.tomoki.config.UserId;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

//产品库存详细信息
public class ProductDetailsActivity extends AppCompatActivity {

    private TextView nameTextView;
    private TextView innerWidthTextView;
    private TextView outerWidthTextView;
    private TextView tbodyTextView;
    private TextView holeTextView;
    private TextView pbodyTextView;
    private TextView weightTextView;
    private TextView usableTextView;
    private String userId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_details);

        ImageButton myBreak =findViewById(R.id.breakButton);
        TextView reservation = findViewById(R.id.reservation);
        nameTextView = findViewById(R.id.personalTextId);
        innerWidthTextView = findViewById(R.id.personalTextInnerWidth);
        outerWidthTextView = findViewById(R.id.personalTextOuterWidth);
        tbodyTextView = findViewById(R.id.personalTextTbody);
        holeTextView = findViewById(R.id.personalTextHole);
        pbodyTextView = findViewById(R.id.personalTextPbody);
        weightTextView = findViewById(R.id.personalTextWeight);
        usableTextView = findViewById(R.id.outCanBeBooked);
        userId = UserId.UserId;

        Bundle bundle = this.getIntent().getExtras();
        String id = bundle.getString("id");

        interfaceModule(id);


        //返回按钮
        myBreak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        reservation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBottomDialog();
            }
        });
    }

    //封装的dialog方法
    private void showBottomDialog(){
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_appointment_view,null);
        dialog.setContentView(view);
        EditText promptNumber = view.findViewById(R.id.promptName);
        EditText promptGo = view.findViewById(R.id.promptGo);
        Button promptYes = view.findViewById(R.id.promptYes);
        Window window = dialog.getWindow();
        //点击弹出键盘
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        dialog.findViewById(R.id.promptName);
        promptYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = promptNumber.getText().toString();
                String name = nameTextView.getText().toString();
                String go = promptGo.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = URL.url+"/app/addAppoint";
                            FormBody.Builder params = new FormBody.Builder();
                            params.add("userId",userId);
                            params.add("name",name);
                            params.add("number",number);
                            params.add("go",go);
                            OkHttpClient client = new OkHttpClient()
                                    .newBuilder()
                                    .connectTimeout(200, TimeUnit.SECONDS)
                                    .readTimeout(250, TimeUnit.SECONDS)
                                    .build();
                            Request request = new Request.Builder()
                                    .url(url)
                                    .post(params.build())
                                    .build();
                            Response response = client.newCall(request).execute();
                            String responseDate = response.body().string();
                            try {
                                java.lang.reflect.Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ProductDetailsActivity.this,"预约成功啦", Toast.LENGTH_SHORT);
                                    finish();
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ProductDetailsActivity.this, "出现异常了~~~(>_<)~~~", Toast.LENGTH_SHORT);
                                }
                            });
                        }
                    }
                }).start();

            }
        });

    }

    /**
     * @author 仓友树
     * 接收后端数据，按照id查找产品信息
     */
    private void interfaceModule(String id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
//                    FormBody.Builder params = new FormBody.Builder();
//                    params.add("outUserId",id);
                    String url = URL.url+"/app/getProductById?id="+id;
                    //创造HTTP客户端
                    OkHttpClient client = new OkHttpClient()
                            .newBuilder()
                            .connectTimeout(200, TimeUnit.SECONDS)
                            .readTimeout(250, TimeUnit.SECONDS)
                            .build();
                    //创造http请求
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    //执行发送的指令
                    Response response = client.newCall(request).execute();
                    //获取后端返回的结果
                    String responseDate = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseDate);
                    String name = jsonObject.getString("name");
                    String innerWidth = jsonObject.getString("innerWidth");
                    String outerWidth = jsonObject.getString("outerWidth");
                    String tbody = jsonObject.getString("tbody");
                    String hole = jsonObject.getString("hole");
                    String pbody = jsonObject.getString("pbody");
                    String weight = jsonObject.getString("weight");
                    String usable = jsonObject.getString("usable");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            nameTextView.setText(name);
                            innerWidthTextView.setText(innerWidth);
                            outerWidthTextView.setText(outerWidth);
                            tbodyTextView.setText(tbody);
                            holeTextView.setText(hole);
                            pbodyTextView.setText(pbody);
                            weightTextView.setText(weight);
                            usableTextView.setText(usable);
                            Toast.makeText(ProductDetailsActivity.this,"连接成功啦~",Toast.LENGTH_LONG).show();
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ProductDetailsActivity.this,"连接不上网络啦",Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }
}